
// return: {code}    // 1更新 2插入

var path = require('path')
var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var validate = utils.validate;
var ip = utils.ip;
var SqlHelper = utils.SqlHelper;

server.post({ path: routerApi, name: routerApi }, async function (req, res, next) {
    var body = req.body || req.query;
    var cmd = parseInt(body.cmd);
    var sqlHelper = new SqlHelper('checkin_ytvank_1017');

    if (!validate.isName(body.name) || !validate.isPhone(body.phone)) {
        return res.send({ code: 0, msg: '请填写正确的电话和姓名' });
    }

    if (!body.userid) {
        return res.send({ code: 0, msg: '无效请求' });
    }

    if (!body.xb) {
        return res.send({ code: 0, msg: '请填写您的性别' });
    }

    if (!body.old) {
        return res.send({ code: 0, msg: '请填写您的年龄' });
    }

    if (!body.sq) {
        return res.send({ code: 0, msg: '请选择的社区' });
    }

    if (!body.qy) {
        return res.send({ code: 0, msg: '请选择球衣尺寸' });
    }

    if (!body.yd) {
        return res.send({ code: 0, msg: '您未同意活动协议' });
    }

    //  首先判断一下是否超过上线
    var str = "select count(*)num from checkin_ytvank_1017 where sq = ?";
    var dataList = [];
    dataList.push(body.sq);
    let result1 = await sqlHelper.asyncQuery(str, dataList);
    console.log(result1[0].num);
    if (result1[0].num >= 15) {
        return res.send({ code: 0, msg: '报名已达上限' });
    }

    // 判断是否已经报过名
    let userinfo = await sqlHelper.asyncSelect({ openid: body.userid });
    if (userinfo[0]) {
        return res.send({ code: 0, msg: '您已经报名了，无需再次报名' })
    }
    var key = {
        openid: body.userid
    }

    var data = {
        openid: body.userid,
        name: body.name,
        phone: body.phone,
        xb: body.xb,
        old: body.old,
        sq: body.sq, // 社区
        qy: body.qy, // 球衣
        yd: body.yd, // 是否统一协议
    }

    sqlHelper.pushData(key, data, (state, results) => {
        return res.send({ code: state });
    })

})
